﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GUI.KhachHangTraLaiBanBuon
{
    public partial class frmXuLy : Form
    {
        #region Delegate
        public delegate void GetString(Boolean capnhat);
        public GetString GetData;
        public static bool CheckClose = false;
        public static bool checksua = false;
        #endregion
        public bool kiemtra = false;
        private string MaKho = string.Empty;
        private string TenKho = string.Empty;
        private string MaKhachHangTraLai = string.Empty;
        Entities.ChiTietKhachHangTraLaiBanBuon[] chitietkhtralaiBB;
        Entities.ChiTietKhachHangTraLaiBanBuon[] hienthi;
        Entities.ChiTietKhachHangTraLaiBanBuon[] templv;
        Entities.ChiTietKhachHangTraLaiBanBuon save;

        private DateTime date;

        private string hanhDong;
        public string HanhDong
        {
            get { return hanhDong; }
            set { hanhDong = value; }
        }

        private Entities.KhachHangTraLaiBanBuon hoadontralai;
        public Entities.KhachHangTraLaiBanBuon Hoadontralai
        {
            get { return hoadontralai; }
            set { hoadontralai = value; }
        }

        public frmXuLy()
        {
            InitializeComponent();
        }

        public frmXuLy(string hanhDong, Entities.KhachHangTraLaiBanBuon hoadontralai)
        {
            InitializeComponent();
            this.hanhDong = hanhDong;
            this.hoadontralai = hoadontralai;
        }

        #region Cai Dat Kho
        private void LayCaiDatKho()
        {
            try
            {
                SetupConfig.Variable vl = new SetupConfig.Variable();
                vl.HanhDong = "1";
                //vl.HanhDong = "2";
                System.Reflection.Assembly getfile = System.Reflection.Assembly.GetExecutingAssembly();
                vl.FileName = getfile.Location + ".config";
                //vl.KeyName = "ChatService";
                SetupConfig.Variable[] list = SetupConfig.Config.GetConfig(vl);
                this.MaKho = list[0].KeyValue;
                this.TenKho = list[1].KeyValue;
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
        }
        #endregion

        #region Thoát
        private void Thoat()
        {
            try
            {
                kiemtra = true;
                this.Close();
            }
            catch (Exception)
            { }
        }
        #endregion

        #region Lay Ma

        private string GetID()
        {
            string code = string.Empty;
            try
            {
                Entities.GetID id = new Entities.GetID();
                id.TableName = "KhachHangTraLaiBanBuon";
                Entities.GetID get = Common.StaticVariable.InterfaceObject.SelectID(id);
                if (get.ColumnName != null)
                {
                    code = Common.Utilities.ProcessID(get.ColumnName);
                }
                else
                { code = "KHTLBB_0001"; }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                code = "KHTLBB_0001";
            }
            return code;
        }
        #endregion

        #region validate
        public bool Validat()
        {
            try
            {
                if (txtMaHoaDon.Text == "<F4 - Tra cứu>" || txtMaHoaDon.Text.Length == 0)
                {
                    return false;
                }
                //if (txtNguoiTra.Text.Length == 0)
                //{
                //    //MessageBox.Show(Common.MSG.MSG13(lblNguoiNhan.Text), Common.MSG.TieuDe, MessageBoxButtons.OK);
                //    //txtNguoiNhan.Focus();
                //    return false;
                //}
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool ValidateDetails()
        {
            try
            {
                //if (txtMaHangHoa.Text == "<F4 - Tra cứu>" || txtMaHangHoa.Text.Length == 0)
                //{
                //    MessageBox.Show(Common.MSG.MSG13(lbMaHangHoa.Text), Common.MSG.TieuDe, MessageBoxButtons.OK);
                //    txtMaHangHoa.Focus();
                //    return false;
                //}
                //if (txtSoLuong.Text.Length == 0 || txtSoLuong.Text == "0")
                //{
                //    MessageBox.Show(Common.MSG.MSG22("Số lượng"), Common.MSG.TieuDe, MessageBoxButtons.OK);
                //    txtSoLuong.Focus();
                //    return false;
                //}
                //if (txtTenHangHoa.Text.Length == 0)
                //{
                //    MessageBox.Show(Common.MSG.MSG13(lbMaHangHoa.Text), Common.MSG.TieuDe, MessageBoxButtons.OK);
                //    txtSoLuong.Focus();
                //    return false;
                //}
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion

        #region xử lý object



        public Entities.KhachHangTraLaiBanBuon XuLyObject(string hanhDong)
        {
            try
            {
                if (Validat())
                {
                    Entities.KhachHangTraLaiBanBuon khTraLaiBB = new Entities.KhachHangTraLaiBanBuon();
                    khTraLaiBB.HanhDong = hanhDong;
                    khTraLaiBB.MaKhachHangTraLaiBanBuon = MaKhachHangTraLai;
                    khTraLaiBB.NgayNhap = date.Date;
                    khTraLaiBB.MaKhachHang = txtMaKhachHang.Text;
                    khTraLaiBB.TenKhachHang = txtTenKhachHang.Text;
                    khTraLaiBB.DuNo = txtNoHienThoi.Text;
                    khTraLaiBB.NguoiTra = txtNguoiTra.Text;
                    khTraLaiBB.MaKho = this.MaKho;
                    khTraLaiBB.TenKho = this.TenKho;
                    khTraLaiBB.MaNhanVien = UtilitiesVariable.User.MaNhanVien;
                    khTraLaiBB.MaTienTe = "TT_0001";
                    khTraLaiBB.TienBoiThuong = "0";
                    khTraLaiBB.ThanhToanNgay = txtThanhToanNgay.Text;
                    khTraLaiBB.ThanhToanSauKhiLapPhieu = "0";
                    khTraLaiBB.Thue = "0";
                    khTraLaiBB.Deleted = false;
                    khTraLaiBB.GhiChu = txtGhiChu.Text;
                    return khTraLaiBB;
                }
                return null;
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region thêm row
        void AddRow()
        {
            if (hanhDong != "Them") return;
            {
                try
                {
                    
                    int sohangtrongbang;
                    hienthi = (Entities.ChiTietKhachHangTraLaiBanBuon[])dgvHienThi.DataSource;
                    // list view = null
                    if (hienthi == null)
                    {
                        templv = new Entities.ChiTietKhachHangTraLaiBanBuon[1];

                        double dongiadachietkhau = (double.Parse(txtGia.Text)) - (((double.Parse(txtGia.Text)) * double.Parse(txtChietKhau.Text)) / 100);
                        double thuegtgtdachietkhau = (dongiadachietkhau * double.Parse(txtThue.Text)) / 100;
                        double thanhtien = ((dongiadachietkhau + thuegtgtdachietkhau) * double.Parse(txtSoLuong.Text));
                        templv[0] = new Entities.ChiTietKhachHangTraLaiBanBuon(Common.Constants.Insert, 0,this.MaKho, MaKhachHangTraLai, txtMaHoaDon.Text, txtMaHangHoa.Text, Common.StaticVariable.timhanghoatheohdbanbuon.TenHangHoa,
                            txtSoLuong.Text,txtChietKhau.Text,txtChietKhauThuongMai.Text, Common.Utilities.FormatMoney(txtGia.Text),
                            Common.Utilities.FormatMoney(thanhtien.ToString()), txtThue.Text, "", false,(double.Parse(Common.StaticVariable.timhanghoatheohdbanbuon.SoLuongConLai) - double.Parse(txtSoLuong.Text)).ToString() );
                        dgvHienThi.DataSource = templv;
                        GridView();
                        return;
                    }

                    sohangtrongbang = hienthi.Length;
                    // số lượng bảng ghi khác 0
                    if (sohangtrongbang != 0)
                    {
                        for (int j = 0; j < sohangtrongbang; j++)
                        {
                            // nếu tìm được mã đã có trong list view
                            if (txtMaHangHoa.Text.ToUpper() == hienthi[j].MaHangHoa.ToUpper() && txtMaHoaDon.Text == hienthi[j].MaHoaDonBanBuon)
                            {
                                templv = new Entities.ChiTietKhachHangTraLaiBanBuon[sohangtrongbang];
                                break;
                            }
                            // nếu không tìm được
                            else
                                templv = new Entities.ChiTietKhachHangTraLaiBanBuon[sohangtrongbang + 1];
                        }
                    }
                    // số lượng bảng ghi = 0
                    else
                        templv = new Entities.ChiTietKhachHangTraLaiBanBuon[sohangtrongbang + 1];
                    // nếu số lượng bảng ghi khác 0
                    if (templv.Length != 0)
                    {
                        try
                        {
                            // số lượng bảng ghi = số lượng row list view
                            if (templv.Length == hienthi.Length)
                            {
                                SoLuongBangSoLuong(templv, hienthi);
                            }
                            // số lượng bảng ghi không = số lượng row list view
                            else
                            {
                                SoLuongKhacSoLuong(templv, hienthi);
                            }
                        }
                        catch
                        {
                            double dongiadachietkhau = (double.Parse(txtGia.Text)) - (((double.Parse(txtGia.Text)) * double.Parse(txtChietKhau.Text)) / 100);
                            double thuegtgtdachietkhau = (dongiadachietkhau * double.Parse(txtThue.Text)) / 100;
                            double thanhtien = ((dongiadachietkhau + thuegtgtdachietkhau) * double.Parse(txtSoLuong.Text));
                            templv[0] = new Entities.ChiTietKhachHangTraLaiBanBuon(Common.Constants.Insert, 0, this.MaKho, MaKhachHangTraLai, txtMaHoaDon.Text, txtMaHangHoa.Text, Common.StaticVariable.timhanghoatheohdbanbuon.TenHangHoa,
                               txtSoLuong.Text, txtChietKhau.Text, txtChietKhauThuongMai.Text, Common.Utilities.FormatMoney(txtGia.Text),
                                Common.Utilities.FormatMoney(thanhtien.ToString()), txtThue.Text, "", false, (double.Parse(Common.StaticVariable.timhanghoatheohdbanbuon.SoLuongConLai) - double.Parse(txtSoLuong.Text)).ToString());

                        }
                        dgvHienThi.DataSource = templv;
                        GridView();
                    }
                }
                catch
                {
                    return;
                }
                finally
                {
                    checksua = false;
                    txtSoLuong.Text = "";
                    txtMaHangHoa.Text = "";
                    txtMaHangHoa.Focus();
                  
                    txtTongTien.Text = Common.Utilities.FormatMoney(TongTien());
                    double conlai = Convert.ToDouble(TongTien()) - Convert.ToDouble(Common.StaticVariable.timkiemkhachhang.DuNo);
                    txtTienConLai.Text = Common.Utilities.FormatMoney(conlai.ToString());
                    txtThanhToanNgay.Text = txtTienConLai.Text;
                }
            }
        }

        void SoLuongBangSoLuong(Entities.ChiTietKhachHangTraLaiBanBuon[] templv, Entities.ChiTietKhachHangTraLaiBanBuon[] hienthi)
        {
            for (int j = 0; j < templv.Length; j++)
            {
                // nếu mã = mã trong list view
                if (txtMaHangHoa.Text.ToUpper() == hienthi[j].MaHangHoa.ToUpper() && txtMaHoaDon.Text == hienthi[j].MaHoaDonBanBuon)
                {
                    int soluongcu = Convert.ToInt32( hienthi[j].SoLuong);
                    int soluonghientai = soluongcu + Convert.ToInt32(txtSoLuong.Text);
                    if (soluonghientai>Convert.ToInt32( Common.StaticVariable.timhanghoatheohdbanbuon.SoLuong))
                    {
                        MessageBox.Show("Bạn không thể trả lại nhiều hơn số bạn mua");
                        templv[0] = new Entities.ChiTietKhachHangTraLaiBanBuon(Common.Constants.Insert, 0, this.MaKho, MaKhachHangTraLai, hienthi[j].MaHoaDonBanBuon, hienthi[j].MaHangHoa, hienthi[j].TenHangHoa,
                       hienthi[j].SoLuong, hienthi[j].PhanTramChietKhau, hienthi[j].PhanTramChietKhauThuongMai, hienthi[j].DonGia,
                        hienthi[j].ThanhTien, hienthi[j].Thue, "", false, hienthi[j].SoLuongConLai);
                        return;
                    }
                    double dongiadachietkhau = (double.Parse(txtGia.Text)) - (((double.Parse(txtGia.Text)) * double.Parse(txtChietKhau.Text)) / 100);
                    double thuegtgtdachietkhau = (dongiadachietkhau * double.Parse(txtThue.Text)) / 100;
                    double thanhtien = ((dongiadachietkhau + thuegtgtdachietkhau) * double.Parse(txtSoLuong.Text));
                    templv[0] = new Entities.ChiTietKhachHangTraLaiBanBuon(Common.Constants.Insert, 0, this.MaKho, MaKhachHangTraLai, txtMaHoaDon.Text, txtMaHangHoa.Text, Common.StaticVariable.timhanghoatheohdbanbuon.TenHangHoa,
                        soluonghientai.ToString(), txtChietKhau.Text, txtChietKhauThuongMai.Text, Common.Utilities.FormatMoney(txtGia.Text),
                        Common.Utilities.FormatMoney(thanhtien.ToString()), txtThue.Text, "", false, (double.Parse(Common.StaticVariable.timhanghoatheohdbanbuon.SoLuongConLai) - double.Parse(txtSoLuong.Text)).ToString());

                }
                // nếu mã không = mã trong list view
                else
                    templv[j] = new Entities.ChiTietKhachHangTraLaiBanBuon(Common.Constants.Insert, 0, this.MaKho, MaKhachHangTraLai, hienthi[j].MaHoaDonBanBuon, hienthi[j].MaHangHoa, hienthi[j].TenHangHoa,
                       hienthi[j].SoLuong, hienthi[j].PhanTramChietKhau, hienthi[j].PhanTramChietKhauThuongMai, hienthi[j].DonGia,
                        hienthi[j].ThanhTien, hienthi[j].Thue, "", false, hienthi[j].SoLuongConLai);

            }
        }

        void SoLuongKhacSoLuong(Entities.ChiTietKhachHangTraLaiBanBuon[] templv, Entities.ChiTietKhachHangTraLaiBanBuon[] hienthi)
        {
            for (int j = 0; j < templv.Length; j++)
            {
                // lấy lại số bảng ghi trên list view
                if (j < templv.Length - 1)
                    templv[j] = new Entities.ChiTietKhachHangTraLaiBanBuon(Common.Constants.Insert, 0, this.MaKho, MaKhachHangTraLai, hienthi[j].MaHoaDonBanBuon, hienthi[j].MaHangHoa, hienthi[j].TenHangHoa,
                       hienthi[j].SoLuong, hienthi[j].PhanTramChietKhau, hienthi[j].PhanTramChietKhauThuongMai, hienthi[j].DonGia,
                        hienthi[j].ThanhTien, hienthi[j].Thue, "", false, hienthi[j].SoLuongConLai);
                // bảng ghi cuối cùng là mới insert vào
                else
                {
                    double dongiadachietkhau = (double.Parse(txtGia.Text)) - (((double.Parse(txtGia.Text)) * double.Parse(txtChietKhau.Text)) / 100);
                    double thuegtgtdachietkhau = (dongiadachietkhau * double.Parse(txtThue.Text)) / 100;
                    double thanhtien = ((dongiadachietkhau + thuegtgtdachietkhau) * double.Parse(txtSoLuong.Text));
                    templv[j] = new Entities.ChiTietKhachHangTraLaiBanBuon(Common.Constants.Insert, 0, this.MaKho, MaKhachHangTraLai, txtMaHoaDon.Text, txtMaHangHoa.Text, Common.StaticVariable.timhanghoatheohdbanbuon.TenHangHoa,
                       txtSoLuong.Text, txtChietKhau.Text, txtChietKhauThuongMai.Text, Common.Utilities.FormatMoney(txtGia.Text),
                        Common.Utilities.FormatMoney(thanhtien.ToString()), txtThue.Text, "", false, (double.Parse(Common.StaticVariable.timhanghoatheohdbanbuon.SoLuongConLai) - double.Parse(txtSoLuong.Text)).ToString());

                }

            }
        }
        string TongTien()
        {
            double tongtien = 0;
            try
            {
               
                foreach (Entities.ChiTietKhachHangTraLaiBanBuon item in templv)
                {
                    tongtien += double.Parse(item.ThanhTien);
                }
                
                return tongtien.ToString();
            }
            catch
            {
                return tongtien.ToString();
            }
        }
        #endregion
        private void frmXuLy_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            try
            {
                try
                {
                    date = Common.StaticVariable.InterfaceObject.SelectDate();
                }
                catch (Exception)
                {
                    date = DateTime.Now;
                }
                LayCaiDatKho();
                switch (this.hanhDong)
                {
                    case "Them":
                        {
                            this.MaKhachHangTraLai = GetID();
                            GridView();
                        }
                        break;
                    case "Xem":
                        {
                            txtMaKhachHang.Text = hoadontralai.MaKhachHang;
                            txtMaKhachHang.Enabled = false;
                            txtTenKhachHang.Text = hoadontralai.TenKhachHang;
                            txtNguoiTra.Text = hoadontralai.NguoiTra;
                            txtNguoiTra.Enabled = false;
                            txtMaHoaDon.Text = "";
                            txtMaHoaDon.Enabled = false;
                            btnThem.Enabled = false;
                            txtMaHangHoa.Enabled = false;
                            Entities.ChiTietKhachHangTraLaiBanBuon ctkh = new Entities.ChiTietKhachHangTraLaiBanBuon();
                            ctkh.HanhDong = "1";
                            ctkh.MaKhachHangTraLai = hoadontralai.MaKhachHangTraLaiBanBuon;
                            hienthi = Common.StaticVariable.InterfaceObject.SelectChiTietKhachHangTraLaiBanBuon( ctkh);
                            dgvHienThi.DataSource = hienthi;
                            btnGhiLai.Enabled = false;
                            dgvHienThi.Enabled = false;
                            GridView();
                            templv = hienthi;
                            txtTongTien.Text = Common.Utilities.FormatMoney(TongTien());
                            txtThanhToanNgay.Text = Common.Utilities.FormatMoney(hoadontralai.ThanhToanNgay);
                            
                            
                        }
                        break;
                    default:
                        this.Thoat();
                        break;
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
        }


        private Entities.HienThiHangHoaListview timhanghoa;
        #region Hien thi
        private void GridView()
        {
            try
            {
                if (hienthi == null)
                {
                    Entities.ChiTietKhachHangTraLaiBanBuon[] nv = new Entities.ChiTietKhachHangTraLaiBanBuon[0];
                    dgvHienThi.DataSource = nv;
                  //  nv[0].gia
                }
                for (int i = 0; i < dgvHienThi.ColumnCount; i++)
                {
                    dgvHienThi.Columns[i].Visible = false;
                }

                dgvHienThi.Columns["MaHangHoa"].HeaderText = "Tên hàng hóa";
                dgvHienThi.Columns["MaHangHoa"].Visible = true;

                dgvHienThi.Columns["TenHangHoa"].HeaderText = "Tên hàng hóa";
                dgvHienThi.Columns["TenHangHoa"].Visible = true;


                dgvHienThi.Columns["SoLuong"].HeaderText = "Số lượng";
                dgvHienThi.Columns["SoLuong"].Visible = true;

                dgvHienThi.Columns["DonGia"].HeaderText = "Giá";
                dgvHienThi.Columns["DonGia"].Visible = true;
                
                dgvHienThi.Columns["PhanTramChietKhau"].HeaderText = "Chiết khấu";
                dgvHienThi.Columns["PhanTramChietKhau"].Visible = true;
                dgvHienThi.Columns["Thue"].HeaderText = "Thuế";
                dgvHienThi.Columns["Thue"].Visible = true;
                dgvHienThi.Columns["ThanhTien"].HeaderText = "Thành tiền (đã C/K)";
                dgvHienThi.Columns["ThanhTien"].Visible = true;
                dgvHienThi.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dgvHienThi.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            }
            catch (Exception)
            {
            }
        }
        #endregion

        private void txtMaHangHoa_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            { 
                case Keys.F4:
                    {
                        this.TimHangHoa();
                    }
                    break;
                case Keys.Enter:
                    { 
                    
                    }
                    break;
            }
        }
        string ChietKhauThuongMai = "0";
        private void TimHangHoa()
        {
            if (Common.StaticVariable.timhoadonbanbuon ==null)
            {
                MessageBox.Show("Bạn cần chọn hóa đơn muốn trả hàng","Thông báo");
                return;
            }
            GUI.TimKiem.frmTimKiemHangHoaTheoHoaDonBanBuon frm = new TimKiem.frmTimKiemHangHoaTheoHoaDonBanBuon(this.txtMaHoaDon.Text.Trim());
            frm.ShowDialog();
            if (Common.StaticVariable.timhanghoatheohdbanbuon != null)
            { 
                timhanghoa = Common.StaticVariable.timhanghoatheohdbanbuon;
                txtMaHangHoa.Text = timhanghoa.MaHangHoa;
                txtGia.Text = timhanghoa.GiaBanBuon;
                txtSoLuong.Text = timhanghoa.SoLuongConLai ;
                txtChietKhau.Text = timhanghoa.ChietKhau;
                txtChietKhauThuongMai.Text = this.ChietKhauThuongMai;

            }
        }
        private void txtMaKhachHang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F4)
            {
                this.TimKhachHang();
            }
        }

        private void TimKhachHang()
        {
            GUI.TimKiem.frmTimKhachHangTraLaiHang frm = new TimKiem.frmTimKhachHangTraLaiHang();
            frm.ShowDialog(this);
            if (Common.StaticVariable.timkiemkhachhang == null)
            {
                return;
            }
            txtMaKhachHang.Text = Common.StaticVariable.timkiemkhachhang.MaKhachHang;
            txtTenKhachHang.Text = Common.StaticVariable.timkiemkhachhang.Ten;
            txtNoHienThoi.Text = Common.StaticVariable.timkiemkhachhang.DuNo;
        }
        private void TimHoaDon()
        {
            if (Common.StaticVariable.timkiemkhachhang == null)   
            {
                MessageBox.Show("Bạn cần chọn khách hàng","Thông báo");
                return;
            }
            GUI.TimKiem.frmTimKiemHoaDonBanBuon frm = new TimKiem.frmTimKiemHoaDonBanBuon(this.MaKho,Common.StaticVariable.timkiemkhachhang.MaKhachHang);
            frm.ShowDialog();
            if (Common.StaticVariable.timhoadonbanbuon==null)
            {
                return;
            }
            txtMaHoaDon.Text = Common.StaticVariable.timhoadonbanbuon.MaHDBanBuon;
            txtGhiChu.Text = Common.StaticVariable.timhoadonbanbuon.GhiChu;
        }

        private void txtMaHoaDon_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F4)
            {
                this.TimHoaDon();
            }
        }

        private void btnKhachHang_Click(object sender, EventArgs e)
        {
            this.TimKhachHang();
        }

        private void btnHoaDon_Click(object sender, EventArgs e)
        {
            this.TimHoaDon();
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Thoat();
        }

        private void frmXuLy_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!CheckClose)
                if (MessageBox.Show(Common.MSG.MSG2(), Common.MSG.TieuDe, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    e.Cancel = CheckClose;
                else
                    e.Cancel = !CheckClose;
            else
            {
                GetData(kiemtra);
            }
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            XuLyEnter_SoLuong();
        }
        void XuLyEnter_SoLuong()
        {
            try
            {

                AddRow();
            }
            catch
            {
            }
        }

        private void dgvHienThi_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            SuaRow();
        }

        private void dgvHienThi_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (hanhDong != "Them")
                return;
            try
            {
                i = e.RowIndex;
                if (i < 0)
                    return;
                if (dgvHienThi.RowCount == 0)
                    return;
                save = ((Entities.ChiTietKhachHangTraLaiBanBuon[])dgvHienThi.DataSource)[i];
            }
            catch
            {
            }
        }
        int i = 0;
        private void dgvHienThi_KeyDown(object sender, KeyEventArgs e)
        {
            if (hanhDong != "Them")
                return;
            if (i < 0)
                return;
            if (dgvHienThi.RowCount == 0)
                return;
            save = ((Entities.ChiTietKhachHangTraLaiBanBuon[])dgvHienThi.DataSource)[i];

            switch (e.KeyData)
            {
                case Keys.Enter:
                    {
                        SuaRow();
                        break;
                    }
            }
        }
        #region sửa row
        void SuaRow()
        {
            if (hanhDong != "Them") return;
            {
                try
                {
                    // obj = null
                    if (save == null)
                    {
                        return;
                    }
                    hienthi = (Entities.ChiTietKhachHangTraLaiBanBuon[])dgvHienThi.DataSource;
                    // list view = null
                    if (hienthi == null)
                    {
                        return;
                    }
                    checksua = true;
                    templv = new Entities.ChiTietKhachHangTraLaiBanBuon[hienthi.Length - 1];
                    int sotang = 0;
                    for (int j = 0; j < hienthi.Length; j++)
                    {
                        if (hienthi[j].MaHangHoa.ToUpper() != save.MaHangHoa.ToUpper() || hienthi[j].MaHoaDonBanBuon != save.MaHoaDonBanBuon)
                        {
                            templv[sotang] = new Entities.ChiTietKhachHangTraLaiBanBuon(Common.Constants.Insert, 0,this.MaKho, MaKhachHangTraLai, hienthi[j].MaHoaDonBanBuon, hienthi[j].MaHangHoa.ToUpper(), hienthi[j].TenHangHoa,
                                     hienthi[j].SoLuong, hienthi[j].PhanTramChietKhau,hienthi[j].PhanTramChietKhauThuongMai, hienthi[j].DonGia, hienthi[j].ThanhTien, hienthi[j].Thue, "", false,hienthi[j].SoLuong );
                            sotang++;
                        }
                        else
                        {
                            txtSoLuong.Text = hienthi[j].SoLuong;
                           //txtTenHangHoa.Text = hienthi[j].TenHangHoa;
                            txtMaHangHoa.Text =hienthi[j].MaHangHoa;
                            txtGia.Text = hienthi[j].DonGia;
                            txtChietKhau.Text = hienthi[j].PhanTramChietKhau;
                            txtChietKhauThuongMai.Text = hienthi[j].PhanTramChietKhauThuongMai;
                            txtThue.Text = hienthi[j].Thue;
                        }
                    }
                    dgvHienThi.DataSource = templv;
                    GridView();
                    save = null;
                    txtSoLuong.Focus();
                    txtSoLuong.SelectAll();

                }
                catch
                {
                }
                finally
                {
                    txtTongTien.Text = Common.Utilities.FormatMoney(TongTien());
                    double conlai = Convert.ToDouble(TongTien()) - Convert.ToDouble(Common.StaticVariable.timkiemkhachhang.DuNo);
                    txtTienConLai.Text = Common.Utilities.FormatMoney(conlai.ToString());
                    txtThanhToanNgay.Text = txtTienConLai.Text;
                    txtSoLuong.Focus();
                    txtSoLuong.SelectAll();
                }
            }
        }

#endregion
        #region Check Conflic Insert
        string matralaiBB;
        public bool CheckConflicInsert(Entities.KhachHangTraLaiBanBuon khtlbb)
        {
            matralaiBB = GetID();
            if (khtlbb.MaKhachHangTraLaiBanBuon == matralaiBB)
            {
                return true;
            }
            return false;
        }
        #endregion
        void GhiLai()
        {
            try
            {
                chitietkhtralaiBB = (Entities.ChiTietKhachHangTraLaiBanBuon[])dgvHienThi.DataSource;
                // check object
                if (chitietkhtralaiBB == null || chitietkhtralaiBB.Length == 0)
                {
                    MessageBox.Show(Common.MSG.MSG37(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return;
                }
               // TinhThue();
                if ( hoadontralai == null)
                {
                    hoadontralai = XuLyObject("Them");
                    if (hoadontralai == null)
                    {
                        return;
                    }
                }

                // check conflic insert
                if (!CheckConflicInsert(hoadontralai))
                {
                    MessageBox.Show(Common.MSG.MSG5(hoadontralai.MaKhachHangTraLaiBanBuon), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    GetData(true);
                    hoadontralai.MaKhachHangTraLaiBanBuon = MaKhachHangTraLai;
                    foreach (Entities.ChiTietKhachHangTraLaiBanBuon item in chitietkhtralaiBB)
                    {
                        item.MaKhachHangTraLai = MaKhachHangTraLai;
                    }
                    return;
                }

                hoadontralai.DanhSach = chitietkhtralaiBB;
                hoadontralai.MaKhachHangTraLaiBanBuon = MaKhachHangTraLai;
                hoadontralai.TyGiaTienTe = "0";
                hoadontralai.TaiKhoan = UtilitiesVariable.User;
                hoadontralai.MaNhanVien = UtilitiesVariable.User.MaNhanVien;
                hoadontralai.TenNhanVien = UtilitiesVariable.User.TenNhanVien;
                if (Common.StaticVariable.InterfaceObject.InsertUpdateKhachHangTraLaiBanBuon(hoadontralai) == 0)
                {
                    MessageBox.Show(Common.MSG.MSG15(hoadontralai.MaKhachHangTraLaiBanBuon), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return;
                }
                CheckClose = true;
                this.Close();

            }
            catch
            {
            }
        }
        private void btnGhiLai_Click(object sender, EventArgs e)
        {
            GhiLai();
        }
    }
}
